//
//  ZDWAppDelegate.m
//  W2MD
//
//  Created by zhudongwei on 14-8-24.
//  Copyright (c) 2014年 zhudongwei. All rights reserved.
//

#import "ZDWAppDelegate.h"
#import <TestinAgent/TestinAgent.h>
#import "SXModel.h"
#import <AVFoundation/AVFoundation.h>

@implementation ZDWAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //[NSThread sleepForTimeInterval:3.0];
    [TestinAgent init:@"184212cfd50a8fd29f97178fbcdad15b" channel:@"您应用的渠道号"];
    [TestinAgent setUserInfo:@"hmy_1122@163.com"];
    
    /*
     @try {
     <#Code that can potentially throw an exception#>
     }
     @catch (NSException *exception) {
     [TestinAgent reportException:exception massage:@"自定义上报信息"];
     }
     @finally {
     <#Code that gets executed whether or not an exception is thrown#>
     }
    */
    // Override point for customization after application launch.
    
    
//    NSError *setCategoryErr = nil;
//    NSError *activationErr  = nil;
//    [[AVAudioSession sharedInstance]
//     setCategory: AVAudioSessionCategoryPlayback
//     error: &setCategoryErr];
//    [[AVAudioSession sharedInstance]
//     setActive: YES
//     error: &activationErr];
    
//    //里面申请backgroundTask
//    
//    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
//    
//    //实现一个可以运行几分钟的权限。
//    
//    //然后写一个计时器实时检测 backgroundTimeRemaining
//    [self tik];
//    
//    
//    [[CKAudioTool sharedInstance] playSound];//这段代码是去播放了一个无声的音乐，很关键的一点是
//    
//    NSError *error=nil;
//    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error];
    
    //注册本地通知
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }
    
    //接收通知参数
    UILocalNotification *notification=[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (notification) {
        NSLog(@"打开应用了");
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"打开应用了"
//                                                        message:notification.alertBody
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil];
//        [alert show];
        SXModel *model=[SXModel shareModel];
        model.noti=YES;
        model.notificaiton=notification;
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        //[self cancelNoti];
    }
    
    if ([[UIApplication sharedApplication] scheduledLocalNotifications].count>0) {
        NSLog(@"you %@",[[UIApplication sharedApplication] scheduledLocalNotifications]);
    } 
        
    //[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    return YES;
}

- (void)tik{
    
    if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 61.0) {
        
        //[[CKAudioTool sharedInstance] playSound];
        
        [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
        
    }
    
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification

{
    NSLog(@"?!?!??!?!?!?!?!?!application");
    SXModel *model=[SXModel shareModel];
    model.noti=YES;
    model.notificaiton=notification;
    UIApplicationState state = application.applicationState;
    
    if (state == UIApplicationStateActive)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"闹钟响了"
                                                        message:notification.alertBody
                                                       delegate:self
                                              cancelButtonTitle:@"确定" 
                                              otherButtonTitles:nil]; 
        [alert show];
        
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SELECT" object:nil];
    //这里，你就可以通过notification的useinfo，干一些你想做的事情了
    
    //application.applicationIconBadgeNumber--;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //[self cancelNoti];
    
}

- (void)cancelNoti
{
    //当前的时间
    //获取系统是24小时制或者12小时制
    NSDate *date=[NSDate date];
    NSCalendar *calendar=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComp=[calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
    
    NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
    NSRange containsA = [formatStringForHours rangeOfString:@"a"];
    BOOL hasAMPM = containsA.location != NSNotFound;
    //hasAMPM==TURE为12小时制，否则为24小时制
    
    NSString *dateStr1=nil;
    if (hasAMPM) {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm:ss"]; // 这里是用大写的H就是24小时制
        dateStr1 = [dateFormatter stringFromDate:date];
    }
    NSInteger hour=[[dateStr1 substringToIndex:2] integerValue];
    NSInteger minute=[dateComp minute];
    
    for (UILocalNotification *noti in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
        if ([[noti.userInfo valueForKey:@"key"] isEqualToString:[NSString stringWithFormat:@"%ld:%ld",(long)hour,(long)minute]]) {
            [[UIApplication sharedApplication] cancelLocalNotification:noti];
        }
    }
}

#pragma mark 进入前台后设置消息信息
-(void)applicationWillEnterForeground:(UIApplication *)application{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
//    UIApplication*   app = [UIApplication sharedApplication];
//    __block    UIBackgroundTaskIdentifier bgTask;
//    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (bgTask != UIBackgroundTaskInvalid)
//            {
//                bgTask = UIBackgroundTaskInvalid;
//            }
//        });
//    }];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (bgTask != UIBackgroundTaskInvalid)
//            {
//                bgTask = UIBackgroundTaskInvalid;
//            }
//        });
//    });
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
